#!/bin/bash

function error () {
    echo "$@" 1>&2
    exit 1
}

function usage () {
    echo "$@" 1>&2
    error "Usage: $0 [ -prefix <dir> ] [ -bindir <dir> ] [ -libdir <dir> ] \
[ -mandir <dir> ]"
}

function check_command () {
    which "$1" > /dev/null
    if [ $? -ne 0 ]; then
	error "Error: \"$1\" not installed"
    fi
}

###

check_command "ocamlc"
check_command "ocamlopt"
check_command "ocamlbuild"
check_command "ocamldep"
check_command "ocamldoc"

###

OCAMLC=$(which ocamlc.opt 2> /dev/null || which ocamlc)
OCAMLOPT=$(which ocamlopt.opt 2> /dev/null || which ocamlopt)
OCAMLBUILD=$(which ocamlbuild.opt 2> /dev/null || which ocamlbuild)
OCAMLDEP=$(wich ocamldep.opt 2> /dev/null || which ocamldep)
OCAMLDOC=$(wich ocamldoc.opt 2> /dev/null || which ocamldoc)
VERSION=$(cat VERSION)
PWD=$(pwd)

###

OCAMLSTDLIB=$($OCAMLC -where)
BINDIR=/usr/local/bin
LIBDIR=$OCAMLSTDLIB/lazy-ocaml
MANDIR=/usr/local/man

while [ $# -ne 0 ]; do
    case "$1" in
	-bindir)   BINDIR="$2"; shift ;;
	-libdir)   LIBDIR="$2"; shift ;;
	-mandir)   MANDIR="$2"; shift ;;
	-prefix)
	    BINDIR="$2"/bin
	    LIBDIR="$2"/lib/lazy-ocaml
	    MANDIR="$2"/man
	    shift;;
	*)
	usage "Don't know what to do with \"$1\""
    esac
    shift
done

###

echo -n "\
VERSION = $VERSION

OCAMLC = $OCAMLC
OCAMLOPT = $OCAMLOPT
OCAMLBUILD = $OCAMLBUILD
OCAMLDEP = $OCAMLDEP
OCAMLDOC = $OCAMLDOC

BINDIR = $BINDIR
LIBDIR = $LIBDIR
MANDIR = $MANDIR/man1

BIN = $PWD/bin
DIST = $PWD/dist
ETC = $PWD/etc
LIB = $PWD/lib
MAN = $PWD/man
SRC = $PWD/src
TESTS = $PWD/tests
" > etc/Makefile.conf

###

echo -n "\
let version = \"$VERSION\"

let ocamlc = \"$OCAMLC\"
let ocamlopt = \"$OCAMLOPT\"
let ocamlbuild = \"$OCAMLBUILD\"
let ocamldep = \"$OCAMLDEP\"
let ocamldoc = \"$OCAMLDOC\"

let bindir = \"$BINDIR\"
let libdir = \"$LIBDIR\"
let mandir = \"$MANDIR/man1\"

let bin = \"$PWD/bin\"
let dist = \"$PWD/dist\"
let etc = \"$PWD/etc\"
let lib = \"$PWD/lib\"
let man = \"$PWD/man\"
let src = \"$PWD/src\"
let tests = \"$PWD/tests\"
" > etc/autoconfig.ml

###

echo "** lazy-ocaml configuration completed successfully **"
